package com.carrot.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.carrot.common.core.domain.dto.PointInfoObjDataDto;
import com.carrot.common.core.domain.entity.SysPointInfoObj;
import com.carrot.common.exception.ServiceException;
import com.carrot.common.mybatis.BaseServiceImpl;
import com.carrot.common.utils.WrapperUtil;
import com.carrot.system.mapper.SysPointInfoObjMapper;
import com.carrot.system.service.IPointInfoObjService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class PointInfoObjServiceImpl extends BaseServiceImpl<SysPointInfoObjMapper, SysPointInfoObj>
        implements IPointInfoObjService {

    @Override
    @Transactional(rollbackFor = ServiceException.class)
    public String importData(Long datasetId, List<PointInfoObjDataDto> dataList) {

        if (dataList.isEmpty()) {
            throw new ServiceException("导入点表数据不能为空！");
        }
        // 读取场站的配置
        int failureNum = 0;

        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();

        // 先按照数据集删除
        UpdateWrapper<SysPointInfoObj> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("dataset_id", datasetId);
        this.remove(updateWrapper);

        try {
            List<SysPointInfoObj> list = WrapperUtil.transform(dataList, SysPointInfoObj.class);
            list.forEach(infoObj -> infoObj.setDatasetId(datasetId));
            this.saveBatch(list);

            successMsg.append("<br/>").append(list.size()).append("、导入成功");
        } catch (Exception e) {
            failureNum++;
            String msg = "<br/>" + failureNum + "、导入失败：";
            failureMsg.append(msg).append(e.getMessage());
        }

        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + dataList.size() + " 条，数据如下：");
        }
        return successMsg.toString();

    }
}
